package com.sixth.service.impl;

import com.sixth.annotation.PageInfoAdvice;
import com.sixth.bean.MarketCollect;
import com.sixth.bean.MarketCollectExample;
import com.sixth.bean.common.BasePageInfo;
import com.sixth.bean.vo.WxCollectListVo;
import com.sixth.constant.Constant;
import com.sixth.mapper.MarketCollectMapper;
import com.sixth.mapper.MarketGoodsMapper;
import com.sixth.service.WxCollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @ClassName WxCollectServiceImpl
 * @Description TODO
 * @Author XiaoWJ
 * @Date 2022/9/11 13:28
 **/
@Transactional
@Service
public class WxCollectServiceImpl implements WxCollectService {

    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Autowired
    MarketCollectMapper marketCollectMapper;


    @PageInfoAdvice
    @Override
    public Object list(BasePageInfo basePageInfo, Integer type, Integer userId) {

        List<WxCollectListVo> wxCollectListVo = marketCollectMapper.selectUserCollectByType(type, userId);

        return wxCollectListVo;
    }

    @Override
    public int addOrDelete(Byte type, Integer valueId, Integer userId) {
        MarketCollectExample example = new MarketCollectExample();

        MarketCollectExample.Criteria criteria = example.createCriteria();

        criteria.andTypeEqualTo(type).andValueIdEqualTo(valueId).andUserIdEqualTo(userId);

        List<MarketCollect> marketCollects = marketCollectMapper.selectByExample(example);

        // 如果收藏表中没有该条收藏数据，则添加该收藏
        if (marketCollects.size() == 0) {
            Date date = new Date();
            int affectRows = marketCollectMapper.insertSelective(new MarketCollect(null, userId, valueId, type, date, date, false));

            return affectRows > 0 ? Constant.OK : Constant.NON;
        }
        // 如果有，则收藏的逻辑删除取反
        MarketCollect marketCollect = marketCollects.get(0);

        // 更新收藏时间

        marketCollect.setUpdateTime(new Date());
        Boolean deleted = marketCollect.getDeleted();

        deleted = (deleted == true) ? false : true;

        marketCollect.setDeleted(deleted);

        int affectRows2 = marketCollectMapper.updateByExampleSelective(marketCollect, example);

        return affectRows2 > 0 ? Constant.OK : Constant.NON;
    }
}
